#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import Any

from cta.interface.action.filter.abstract_filter_action import AbstractFilterAction
from web.constants.datetime_format import DatetimeFormat
from web.domain.responsibility_chain_dto import ResponsibilityChainDto
from web.models.commodity_future_date_contract_data import CommodityFutureDateContractData
from web.models.quant2_commodity_future_filter import Quant2CommodityFutureFilter
from web.util.datetime_util import DatetimeUtil
from web.manager.log_manager import LogManager

Logger = LogManager.get_logger(__name__)


class UpdateUpDownPercentageWithinDateFilterAction(AbstractFilterAction):
    """
    更新每个品种过去n天的涨跌百分比
    """

    def exec(self, responsibility_chain_dto: ResponsibilityChainDto = None):

        transaction_date: str = responsibility_chain_dto.transaction_date

        # 计算回溯日期
        up_down_percentage_n_date: int = self.calculate_up_down_percentage_backtrack_date(transaction_date)

        Logger.info("更新每个品种过去[%d]天的涨跌百分比", up_down_percentage_n_date)

        quant2_commodity_future_filter_list: list[Quant2CommodityFutureFilter] = self.quant2_commodity_future_filter_dao.find_list(dict(), dict(), list())
        if quant2_commodity_future_filter_list is not None and len(quant2_commodity_future_filter_list):
            for quant2_commodity_future_filter in quant2_commodity_future_filter_list:
                # 查询具体合约最近的n条记录
                commodity_future_date_contract_data_list: list[CommodityFutureDateContractData] = self.commodity_future_date_contract_data_dao.find_by_code_and_before_n_transaction_date_order_by_transaction_date_desc(
                    quant2_commodity_future_filter.code, transaction_date, up_down_percentage_n_date)

                if commodity_future_date_contract_data_list is None or len(commodity_future_date_contract_data_list) < up_down_percentage_n_date:
                    Logger.warning('期货[%s]的总交易记录数小于[%d]，删除这条记录', quant2_commodity_future_filter.code, up_down_percentage_n_date)

                    self.quant2_commodity_future_filter_dao.delete(quant2_commodity_future_filter)

                    continue

                first_commodity_future_date_contract_data: CommodityFutureDateContractData = commodity_future_date_contract_data_list[0]
                end_commodity_future_date_contract_data: CommodityFutureDateContractData = commodity_future_date_contract_data_list[len(commodity_future_date_contract_data_list) - 1]
                up_down_percentage: float = (first_commodity_future_date_contract_data.close_price - end_commodity_future_date_contract_data.close_price) / end_commodity_future_date_contract_data.close_price * 100

                # 更新up_down_percentage_with_n_date字段
                quant2_commodity_future_filter.up_down_percentage_with_n_date = up_down_percentage
                self.quant2_commodity_future_filter_dao.update(quant2_commodity_future_filter)

        super().next(responsibility_chain_dto)